package com.rockymew.business.controller.sample;

import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JPanel;

import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.util.DOMUtilities;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.util.XMLResourceDescriptor;
import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.svg.SVGDocument;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rockymew.business.dao.entity.Sample;
import com.rockymew.business.dao.mapper.SampleMapper;
import com.rockymew.core.exception.BusinessCoreException;
import com.rockymew.core.mybatis.paging.Page;
import com.rockymew.core.wsresult.WsResult;
import com.rockymew.utils.Tools;

@Controller
public class SampleController {
    // @Resource SampleService sampleService;
    @Resource
    SampleMapper sampleMapper;

    private final String[] GENES_BODY = { "bomei", "hashiqi", "xueruina", "", "", "", "", "", "", "", "", "",
            "qiutianquan", "samoye", "jiwawa", "bage", "bianmu", "", "", "", "", "", "jinmao", "bandian", "", "", "",
            "changbandian", "", "", "", "" };

    private final String[] GENES_PATTERN = { "shuangtiaowen", "", "bage", "", "jianduanbankuai", "xiongcebankuai",
            "duotiaowen", "tiaowenjianban", "qiutianquan", "hashiqi", "xueruina", "", "bandian", "banbankuai", "jiwawa",
            "bianmuhuawen", "", "", "quanshenbankuai", "duotiaowenjianban", "hudieban", "", "xingyunhuan", "huanxiong",
            "bankuaishengji", "huawenshengji", "", "xiongmao", "bantiaojiehe", "", "", "" };

    private final String[] GENES_EYECOLOR = { "thundergrey", "gold", "topaz", "mintgreen", "", "sizzurp", "chestnut",
            "strawberry", "sapphire", "forgetmenot", "white", "", "", "", "", "", "pumpkin", "limegreen", "",
            "bubblegum", "twilightsparkle", "", "", "", "babypuke", "", "chunse", "", "", "", "", "" };
    private final String[] GENES_EYETYPE = { "", "yuanyan", "fadai", "", "fanu", "", "", "", "", "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };

    private final String[] GENES_BODECOLOR = { "shadowgrey", "salmon", "", "orangesoda", "cottoncandy", "mauveover",
            "aquamarine", "nachocheez", "", "", "greymatter", "", "", "", "hintomint", "bananacream", "cloudwhite", "",
            "oldlace", "koala", "", "", "", "verdigris", "", "onyx", "", "", "chunse", "", "", "" };

    private final String[] GENES_PATCOLOR = { "", "", "", "", "lilac", "apricot", "royalpurple", "", "swampgreen",
            "violet", "scarlet", "barkbrown", "coffee", "lemonade", "chocolate", "", "", "", "turtleback", "",
            "wolfgrey", "cerulian", "skyblue", "", "", "", "royalblue", "", "chunse", "", "", "" };

    private final String[] GENES_SECONDCOLOR = { "bkg_1", "", "bkg_3", "", "", "", "", "", "", "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };

    private final String[] GENES_WILD = { "wild_1", "", "wild_3", "wild_4", "", "wild_6", "", "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };

    private final String[] GENES_MOUTH = { "bizui", "", "ciya", "", "", "shengqi", "", "", "", "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };

    @RequestMapping(value = "/createkitty.do", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object sample1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // String genes = request.getParameter("genes");
        //
        // String kittyid = request.getParameter("kittyid");
        // JSONObject object = new JSONObject();
        // String allGensStrings = "";
        // for (int i = 0; i < 6; i++) {
        // kittyid = "" + i;
        // // genes = createKittyGenes(request);
        // genes = createCommonKittyGenes(request);
        //
        // int secondColor = createKittyByGenes(request, genes, kittyid);
        //
        // String bkg = GENES_SECONDCOLOR[secondColor];
        //
        // object.put("background", bkg);
        // allGensStrings += "Kitty" + i + " Genes:" + genes + "\r\n";
        //
        // }
        // String currentPath = Tools.currentPath(request);
        // String filePath = currentPath + "image/gene.json";
        // writeFile(filePath, allGensStrings);

        // genesPromoPup(request);
        // createVipDogs(request);
        // puregen0Test(request);
        // genes0Siring(request);
        // genes1Siring(request);
        // getDattributes("00001084210842108422800008422294a05ad6b080102104149c008c2186b5ad");
        // lowgenesCreateBylow(request);
        // createDogs(request);
        genes0Special48(request);
         createVipDogs(request);
        return WsResult.success("OK");
    }

    // @RequestMapping(value = "/createkitty.do", produces = {
    // MediaType.APPLICATION_JSON_VALUE })
    // @ResponseBody
    // public Object sample(HttpServletRequest request, HttpServletResponse
    // response) throws IOException {
    // String genes = request.getParameter("genes");
    // if
    // (genes.equals("00005ad2b318e6724ce4b9290146531884721ad18c63298a5308a55ad6b6b58d"))
    // {
    // return WsResult.success("OK");
    // }
    // String kittyid = request.getParameter("kittyid");
    // JSONObject object = new JSONObject();
    // int secondColor = createKittyByGenes(request, genes, kittyid);
    // String bkg = GENES_SECONDCOLOR[secondColor];
    // object.put("background", bkg);
    // return WsResult.success("OK", object);
    // }

    public static void writeFile(String filePath, String sets) throws IOException {
        FileWriter fw = new FileWriter(filePath);
        PrintWriter out = new PrintWriter(fw);
        out.write(sets);
        out.println();
        fw.close();
        out.close();
    }

    private int createKittyByGenes(HttpServletRequest request, String genes, String kittyid) {

        String str = genes.toUpperCase();
        byte[] bArray = HexStringToBinary(str);

        String binaryStr = bytes2BinaryStr(bArray);
        int body = getMainBody(binaryStr);
        int pattern = getMainPattern(binaryStr);
        int eyecolor = getMainEyeColor(binaryStr);
        int eyetype = getMainEyeType(binaryStr);
        int bodycolor = getMainBodyColor(binaryStr);
        int petcolor = getMainPatColor(binaryStr);
        int secondColor = getMainSecondColor(binaryStr);
        int wild = getMainWild(binaryStr);
        int mouth = getMainMouth(binaryStr);
        int[] kaiGenes = { body, pattern, eyecolor, eyetype, bodycolor, petcolor, secondColor, wild, mouth };

        createKittyForKai(request, kaiGenes, kittyid, null);

        return secondColor;

    }

    private void setColorForSection(Element element, String colorSection, String colorValue) {

        boolean isFind = false;
        if (element.getAttributeNS(null, "id").equals(colorSection)) {
            isFind = true;
        }

        NodeList childList = element.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node child = childList.item(i);
            String nodeName = child.getNodeName();
            if (nodeName.equals("g") || nodeName.equals("switch")) {
                Element g = (Element) child;
                String arrID = g.getAttributeNS(null, "id");
                if (arrID.equals(colorSection))// 找到相应的g节点，开始换颜色
                {
                    NodeList sectionChildren = g.getChildNodes();
                    for (int j = 0; j < sectionChildren.getLength(); j++) {
                        Node colorNode = sectionChildren.item(j);
                        String colorNodeName = colorNode.getNodeName();
                        if (colorNodeName == "path" || colorNodeName == "circle" || colorNodeName == "ellipse") {

                            Element path = (Element) colorNode;

                            path.setAttributeNS(null, "fill", colorValue);

                        }

                    }
                }
                setColorForSection(g, colorSection, colorValue);
            } else if (isFind) {
                if (nodeName.equals("path") || nodeName == "circle" || nodeName == "ellipse") {
                    Element path = (Element) child;

                    path.setAttributeNS(null, "fill", colorValue);
                }

            }

        }

    }

    @RequestMapping(value = "/testcreate.do", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object testcreate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String genes = request.getParameter("genes");
        int[] dogpart = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        int index = 0;
        for (int i = genes.length() - 1; i >= 0;) {
            int temp = genes.charAt(i);
            dogpart[index] = kai2Int(temp);
            index++;
            i -= 4;
        }

        int body = dogpart[0];
        int pattern = dogpart[1];
        int eyecolor = dogpart[2];
        int eyetype = dogpart[3];
        int bodycolor = dogpart[4];
        int petcolor = dogpart[5];
        int secondColor = dogpart[6];
        int wild = dogpart[7];
        int mouth = dogpart[8];
        int[] kaiGenes = { body, pattern, eyecolor, eyetype, bodycolor, petcolor, secondColor, wild, mouth };
        String currentPath = Tools.currentPath(request);

        String filePath = currentPath + "testimage/";
        createDir(filePath);

        File file = new File(filePath);
        File[] listfile = file.listFiles();
        String kittyID = "" + (listfile.length + 1);

        String SvgFilePath = filePath + kittyID + ".svg";

        createKittyForKai(request, kaiGenes, kittyID, SvgFilePath);
        int[] kaiGens = new int[48];

        for (int i = 0; i < genes.length(); i++) {
            kaiGens[i + 12] = kai2Int(genes.charAt(i));

        }

        String binaryStr = "";
        for (int m = 0; m < 48; m++) {
            binaryStr += toBinaryString(kaiGens[m]);
        }
        String hexString = binaryString2hexString(binaryStr);
        String newGenes = "1000" + hexString;
        JSONObject object = new JSONObject();
        object.put("genes", newGenes);
        object.put("petId", kittyID);

        return WsResult.success("OK", object);
    }

    private int kai2Int(int genes) {
        if (genes >= '0' && genes <= '9') {
            return genes - '0';
        } else if (genes >= 'a' && genes <= 'k') {
            return genes - 'a' + 9;
        } else if (genes >= 'm' && genes <= 'x') {
            return genes - 'm' + 20;
        }
        return 0;
    }

    private String imagePath = null;

    private void createKittyForKai(HttpServletRequest request, int[] kaiGenes, String kittyID, String svgPath) {
        int body = kaiGenes[0];
        int pattern = kaiGenes[1];
        int eyecolor = kaiGenes[2];
        int eyetype = kaiGenes[3];
        int bodycolor = kaiGenes[4];
        int petcolor = kaiGenes[5];
        int wild = kaiGenes[7];
        int mouth = kaiGenes[8];
        String currentPath = Tools.currentPath(request);
        String commonPath = "file:///" + currentPath + "resource/cattributes/";

        JSONObject colorConfig = getConfigByComm(request, "colorconfig.json");

        //
        // 解析基因完成
        // JFrame f = new JFrame("Batik");
        JPanel p = new JPanel(new BorderLayout());
        JSVGCanvas svgCanvas = new JSVGCanvas();

        p.add(svgCanvas);

        SVGDocument doc = null;
        SVGDocument doc2 = null;
        SVGDocument doc4 = null;
        SVGDocument doc5 = null;
        SVGDocument doc7 = null;
        SVGDocument doc8 = null;
        Element x = null, x3 = null, x4 = null, x6 = null, x7 = null;

        try {
            String parser = XMLResourceDescriptor.getXMLParserClassName();
            SAXSVGDocumentFactory sax = new SAXSVGDocumentFactory(parser);
            String uri = commonPath + "body/" + GENES_BODY[body] + "/bodycolor.svg";

            String uri4 = commonPath + "body/" + GENES_BODY[body] + "/mouth/" + GENES_MOUTH[mouth] + ".svg";
            String uri2 = commonPath + "body/" + GENES_BODY[body] + "/pattern/" + GENES_PATTERN[pattern] + ".svg";// commonPath+"body/"+GENES_BODY[body]+"/"+"body.svg";
            String uri5 = commonPath + "body/" + GENES_BODY[body] + "/body.svg";// commonPath+"wild/"+GENES_WILD[wild]+".svg";;
            String uri7 = commonPath + "body/" + GENES_BODY[body] + "/eyetype/" + GENES_EYETYPE[eyetype] + ".svg";

            String uri8 = commonPath + "body/" + GENES_BODY[body] + "/wild/" + GENES_WILD[wild] + ".svg"; // commonPath+"mouth/"+GENES_MOUTH[mouth]+".svg";
            if (uriIsExist(uri)) {
                doc = sax.createSVGDocument(uri);
            }
            if (uriIsExist(uri2)) {
                doc2 = sax.createSVGDocument(uri2);
            }
            if (uriIsExist(uri4)) {
                doc4 = sax.createSVGDocument(uri4);
            }
            if (uriIsExist(uri5)) {
                doc5 = sax.createSVGDocument(uri5);
            }
            if (uriIsExist(uri7)) {
                doc7 = sax.createSVGDocument(uri7);
            }
            if (uriIsExist(uri8)) {
                doc8 = sax.createSVGDocument(uri8);
            }

            if (doc != null) {
                Element elment = doc.getDocumentElement();
                JSONArray bodycolors = colorConfig.getJSONArray("bodycolor");
                if (bodycolors == null)
                    return;
                JSONObject colorJson = bodycolors.getJSONObject(0);
                if (GENES_BODECOLOR[bodycolor].equals("chunse")) {
                    JSONObject chunseJson = colorJson.getJSONObject(GENES_BODECOLOR[bodycolor]);
                    String colorValue = chunseJson.getString(GENES_BODY[body]);
                    if (colorValue != null) {
                        setColorForSection(elment, "bodycolor", colorValue);
                    }
                } else {
                    String colorValue = colorJson.getString(GENES_BODECOLOR[bodycolor]);
                    setColorForSection(elment, "bodycolor", colorValue);
                }
            }

            if (doc2 != null) {
                x = doc2.getDocumentElement();
                JSONArray patcolors = colorConfig.getJSONArray("patcolor");
                if (patcolors == null)
                    return;
                JSONObject colorJson = patcolors.getJSONObject(0);

                if (GENES_PATCOLOR[petcolor].equals("chunse")) {
                    JSONObject chunseJson = colorJson.getJSONObject(GENES_PATCOLOR[petcolor]);
                    String colorValue = chunseJson.getString(GENES_BODY[body]);
                    if (colorValue != null) {
                        setColorForSection(x, "patcolor", colorValue);
                    }
                } else {
                    String colorValue = colorJson.getString(GENES_PATCOLOR[petcolor]);
                    setColorForSection(x, "patcolor", colorValue);
                    setColorForSection(x, "patcolor1", colorValue);
                }
                JSONArray patcolors2 = colorConfig.getJSONArray("patcolor2");
                if (patcolors2 == null)
                    return;
                JSONObject colorJson2 = patcolors2.getJSONObject(0);

                if (GENES_PATCOLOR[petcolor].equals("chunse")) {
                    JSONObject chunseJson = colorJson2.getJSONObject(GENES_PATCOLOR[petcolor]);
                    String colorValue = chunseJson.getString(GENES_BODY[body]);
                    if (colorValue != null) {
                        setColorForSection(x, "patcolor2", colorValue);
                    }
                } else {
                    String colorValue2 = colorJson2.getString(GENES_PATCOLOR[petcolor]);
                    setColorForSection(x, "patcolor2", colorValue2);
                }

                x = (Element) doc.importNode(x, true);
                doc.getDocumentElement().appendChild(x);
            }

            if (doc4 != null) {
                x3 = doc4.getDocumentElement();
                // x.setNodeValue("svg");

                x3 = (Element) doc.importNode(x3, true);
                doc.getDocumentElement().appendChild(x3);
            }

            if (doc5 != null) {
                x4 = doc5.getDocumentElement();
                // x.setNodeValue("svg");
                x4 = (Element) doc.importNode(x4, true);
                doc.getDocumentElement().appendChild(x4);
            }

            if (doc7 != null) {
                x6 = doc7.getDocumentElement();

                JSONArray eyecolorJson = colorConfig.getJSONArray("eyecolor");
                if (eyecolorJson == null)
                    return;
                JSONObject colorJson = eyecolorJson.getJSONObject(0);
                if (GENES_EYECOLOR[eyecolor].equals("chunse")) {
                    JSONObject chunseJson = colorJson.getJSONObject(GENES_EYECOLOR[eyecolor]);
                    String colorValue = chunseJson.getString(GENES_BODY[body]);
                    if (colorValue != null) {
                        setColorForSection(x6, "eyecolor", colorValue);
                    } else {

                        String colorValue1 = colorJson.getString(GENES_EYECOLOR[eyecolor]);
                        setColorForSection(x6, "eyecolor", colorValue1);

                    }
                }

                x6 = (Element) doc.importNode(x6, true);
                doc.getDocumentElement().appendChild(x6);

            }

            if (doc8 != null) {
                x7 = doc8.getDocumentElement();
                x7 = (Element) doc.importNode(x7, true);
                doc.getDocumentElement().appendChild(x7);
            }

        } catch (IOException ex) {
        }

        p.add(svgCanvas);
        svgCanvas.setVisible(true); // probably not needed.
        svgCanvas.setDocument(doc);
        try {
            if (imagePath == null) {
                JSONObject config = getConfigByComm(request, "config.json");
                if (config != null) {
                    imagePath = config.getString("imagepath");
                }
            }
            String filePath = currentPath + "image/";
            createDir(filePath);
            String fileName = filePath + kittyID + ".svg";
            if (svgPath != null && svgPath.length() > 0) {
                fileName = svgPath;
            }

            File _fPath = new File(fileName);
            if (!_fPath.exists())
                _fPath.createNewFile();

            _fPath.setReadable(true, false);
            _fPath.setWritable(true, false);
            FileOutputStream outStream = new FileOutputStream(fileName);
            Writer outf = new OutputStreamWriter(outStream, "UTF-8");
            DOMUtilities.writeDocument(doc, outf);
            outf.flush();
            outf.close();
        } catch (IOException e) {
        }

    }

    public static boolean createDir(String destDirName) {
        File dir = new File(destDirName);
        if (dir.exists()) {// 判断目录是否存在
            System.out.println("创建目录失败，目标目录已存在！" + destDirName);
            return false;
        }
        if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
            destDirName = destDirName + File.separator;
        }
        if (dir.mkdirs()) {// 创建目标目录
            System.out.println("创建目录成功！" + destDirName);

            return true;
        } else {
            System.out.println("创建目录失败！");
            return false;
        }
    }

    boolean uriIsExist(String uri) {
        try {
            Path path = Paths.get(new URI(uri));
            File file = path.toFile();
            if (file.exists()) {
                return true;
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static String hexStr = "0123456789ABCDEF";
    private static String[] binaryArray = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000",
            "1001", "1010", "1011", "1100", "1101", "1110", "1111" };

    /**
     * 
     * @param hexString
     * @return 将十六进制转换为字节数组
     */
    public static byte[] HexStringToBinary(String hexString) {
        // hexString的长度对2取整，作为bytes的长度
        int len = hexString.length() / 2;
        byte[] bytes = new byte[len];
        byte high = 0;// 字节高四位
        byte low = 0;// 字节低四位

        for (int i = 0; i < len; i++) {
            // 右移四位得到高位
            high = (byte) ((hexStr.indexOf(hexString.charAt(2 * i))) << 4);
            low = (byte) hexStr.indexOf(hexString.charAt(2 * i + 1));
            bytes[i] = (byte) (high | low);// 高地位做或运算
        }
        return bytes;
    }

    /**
     * 
     * @param str
     * @return 转换为二进制字符串
     */
    public static String bytes2BinaryStr(byte[] bArray) {

        String outStr = "";
        int pos = 0;
        for (byte b : bArray) {
            // 高四位
            pos = (b & 0xF0) >> 4;
            outStr += binaryArray[pos];
            // 低四位
            pos = b & 0x0F;
            outStr += binaryArray[pos];
        }
        return outStr;

    }

    private static int getMainBody(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainPattern(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 20 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainEyeColor(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 40 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainEyeType(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 60 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainBodyColor(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 80 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainPatColor(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 100 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainSecondColor(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 120 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainWild(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 140 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getMainMouth(String genes) {
        int length = genes.length();
        if (length == 256) {
            int index = length - 160 - 1;
            return getDominant(genes, index);
        }

        return -1;
    }

    private static int getDominant(String genes, int index) {
        int length = genes.length();

        if (length == 256 && index >= 5 && index < 256) {
            int char1 = genes.charAt(index) - 48;
            int char2 = genes.charAt(index - 1) - 48;
            int char3 = genes.charAt(index - 2) - 48;
            int char4 = genes.charAt(index - 3) - 48;
            int char5 = genes.charAt(index - 4) - 48;

            int body = char5 * 16 + char4 * 8 + char3 * 4 + char2 * 2 + char1;
            return body;
        }
        return -1;
    }

    private JSONObject cattributesObject = null;

    @RequestMapping(value = "/creategenes.do", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    String createKittyGenes(HttpServletRequest request) {
        int[] genes = new int[48];
        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "cattributes.json";
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                cattributesObject = JSONObject.parseObject(input);

            } catch (Exception e) {
                e.printStackTrace();
                cattributesObject = null;
            }
        }

        JSONObject jsonObject = cattributesObject;

        if (jsonObject != null) {
            JSONArray bodys = jsonObject.getJSONArray("body");
            int currentbody = 0;
            // body
            currentbody = randomGenes(bodys, 4, GENES_BODY, genes, 47);
            // pattren
            JSONArray pattrens = jsonObject.getJSONArray("pattern");
            randomGenes(pattrens, 4, GENES_PATTERN, genes, 43);
            // eyecolor
            JSONArray eyecolors = jsonObject.getJSONArray("eyecolor");
            randomGenes(eyecolors, 4, GENES_EYECOLOR, genes, 39);
            // eyetype
            JSONArray eyetypes = jsonObject.getJSONArray("eyetype");
            randomGenes(eyetypes, 4, GENES_EYETYPE, genes, 35);
            // BODY COLOR
            JSONArray bodycolors = jsonObject.getJSONArray("bodycolor");
            randomGenes(bodycolors, 4, GENES_BODECOLOR, genes, 31);
            // PAT COLOR
            JSONArray petColors = jsonObject.getJSONArray("patcolor");
            randomGenes(petColors, 4, GENES_PATCOLOR, genes, 27);
            // SEC COLOR
            JSONArray pupilcolor = jsonObject.getJSONArray("pupilcolor");
            randomGenes(pupilcolor, 4, GENES_SECONDCOLOR, genes, 23);
            // wild 此字段暂时无 临时加的
            JSONArray wildJson = jsonObject.getJSONArray("wild");
            randomGenes(wildJson, currentbody, GENES_WILD, genes, 19);

            // mouth
            JSONArray mouths = jsonObject.getJSONArray("mouth");
            randomGenes(mouths, 4, GENES_MOUTH, genes, 15);

            randomGenes(pupilcolor, 4, GENES_SECONDCOLOR, genes, 11);

            randomGenes(pupilcolor, 4, GENES_SECONDCOLOR, genes, 7);
            randomGenes(pupilcolor, 4, GENES_SECONDCOLOR, genes, 3);

            // System.out.println("genes！" + genes);
            String binaryStr = "";
            for (int m = 0; m < 48; m++) {
                binaryStr += toBinaryString(genes[m]);
            }
            String newGenes = "0000" + binaryString2hexString(binaryStr);
            System.out.println("newGenes！" + newGenes.toString() + "\r\n");
            return newGenes;
        }

        return "";
    }

    String createCommonKittyGenes(HttpServletRequest request) {
        int[] genes = new int[48];
        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "cattributes.json";
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                cattributesObject = JSONObject.parseObject(input);

            } catch (Exception e) {
                e.printStackTrace();
                cattributesObject = null;
            }
        }

        JSONObject jsonObject = cattributesObject;

        if (jsonObject != null) {
            // pattren
            JSONArray pattrens = jsonObject.getJSONArray("pattern");
            randomCommonGenes(pattrens, 13, 4, GENES_PATTERN, genes, 43);
            // eyecolor
            JSONArray eyecolors = jsonObject.getJSONArray("eyecolor");
            randomGenes(eyecolors, 4, GENES_EYECOLOR, genes, 39);
            // eyetype
            JSONArray eyetypes = jsonObject.getJSONArray("eyetype");
            randomGenes(eyetypes, 4, GENES_EYETYPE, genes, 35);
            // BODY COLOR
            JSONArray bodycolors = jsonObject.getJSONArray("bodycolor");
            randomCommonGenes(bodycolors, 10, 4, GENES_BODECOLOR, genes, 31);
            // PAT COLOR
            JSONArray petColors = jsonObject.getJSONArray("patcolor");
            randomCommonGenes(petColors, 10, 4, GENES_PATCOLOR, genes, 27);
            // SEC COLOR
            JSONArray pupilcolor = jsonObject.getJSONArray("pupilcolor");
            for (int s = 0; s < 4; s++) {
                genes[23 - s] = 5;
            }
            for (int s = 0; s < 4; s++) {
                genes[19 - s] = 1;
            }

            // mouth
            JSONArray mouths = jsonObject.getJSONArray("mouth");
            randomGenes(mouths, 4, GENES_MOUTH, genes, 15);

            randomGenes(pupilcolor, 4, GENES_SECONDCOLOR, genes, 11);

            randomGenes(pupilcolor, 4, GENES_SECONDCOLOR, genes, 7);
            randomGenes(pupilcolor, 4, GENES_SECONDCOLOR, genes, 3);

            // System.out.println("genes！" + genes);
            String binaryStr = "";
            for (int m = 0; m < 48; m++) {
                binaryStr += toBinaryString(genes[m]);
            }
            String newGenes = "0000" + binaryString2hexString(binaryStr);

            System.out.println("newGenes！" + newGenes.toString() + "\r\n");
            return newGenes;
        }
        return "";
    }

    public static String binaryString2hexString(String bString) {
        if (bString == null || bString.equals("") || bString.length() % 8 != 0)
            return null;
        StringBuffer tmp = new StringBuffer();
        int iTmp = 0;
        for (int i = 0; i < bString.length(); i += 4) {
            iTmp = 0;
            for (int j = 0; j < 4; j++) {
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
            }
            tmp.append(Integer.toHexString(iTmp));
        }
        return tmp.toString();
    }

    int randomGenes(JSONArray gensArray, int genesCount, String[] constGenes, int[] newGenes, int newGenesIndex) {
        if (gensArray == null) {
            return -1;
        }
        int currentIndex = 0;
        int count = gensArray.size();

        for (int i = 0; i < genesCount; i++) {
            Random random = new Random();

            int s = 0;
            if (count > 1) {
                s = random.nextInt(count) % (count);
            }
            if (i == 0) {
                currentIndex = s;
            }
            JSONObject body = gensArray.getJSONObject(s);
            boolean isfind = false;
            for (int j = 0; j < constGenes.length; j++) {
                if (constGenes[j].equals(body.getString("name"))) {
                    newGenes[newGenesIndex - i] = j;
                    isfind = true;
                    break;
                }
            }
            if (!isfind) {
            }

        }
        return currentIndex;
    }

    int randomCommonGenes(JSONArray gensArray, int gensArrayCount, int genesCount, String[] constGenes, int[] newGenes,
            int newGenesIndex) {
        if (gensArray == null) {
            return -1;
        }
        int currentIndex = 0;
        int count = gensArray.size();
        if (gensArrayCount > 0) {
            count = gensArrayCount;
        }

        for (int i = 0; i < genesCount; i++) {
            Random random = new Random();

            int s = 0;
            if (count > 1) {
                s = random.nextInt(count) % (count);
            }
            if (i == 0) {
                currentIndex = s;
            }
            JSONObject body = gensArray.getJSONObject(s);
            boolean isfind = false;
            for (int j = 0; j < constGenes.length; j++) {
                if (constGenes[j].equals(body.getString("name"))) {
                    newGenes[newGenesIndex - i] = j;
                    isfind = true;
                    break;
                }
            }
            if (!isfind) {
            }

        }
        return currentIndex;
    }

    String toBinaryString(int value) {

        int a1 = value / 16;
        int b1 = value % 16;
        int a2 = b1 / 8;
        int b2 = b1 % 8;
        int a3 = b2 / 4;
        int b3 = b2 % 4;
        int a4 = b3 / 2;
        int b4 = b3 % 2;
        int a5 = b4 % 2;

        StringBuilder sb = new StringBuilder();
        sb.append(a1);
        sb.append(a2);
        sb.append(a3);
        sb.append(a4);
        sb.append(a5);
        return sb.toString();

    }

    private JSONObject getConfigByComm(HttpServletRequest request, String filename) {
        String currentPath = Tools.currentPath(request);
        JSONObject bodyColorJson = null;

        String cattributesPath = currentPath + "resource/" + filename;

        try {
            String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
            bodyColorJson = JSONObject.parseObject(input);

        } catch (Exception e) {
            e.printStackTrace();
            bodyColorJson = null;
        }

        return bodyColorJson;
    }

    @RequestMapping(value = "/exception", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object sampleException() {
        throw new BusinessCoreException("出错了");
    }

    @RequestMapping(value = "/tran", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object sampleTran() {
        // sampleService.tranTest();
        return WsResult.success("成功了");
    }

    @RequestMapping(value = "/tranok", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object sampleTranOk() {
        // / sampleService.tranTestOk();
        return WsResult.success("成功了");
    }

    @RequestMapping(value = "/page", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object samplePage(@RequestParam("p") Integer p, @RequestParam("s") Integer s) {
        Page page = new Page(p, s);
        List<Sample> data = sampleMapper.selectPaging(page);
        return WsResult.success("成功了", data);
    }

    @RequestMapping(value = "/all", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object sampleAll() {
        List<Sample> data = sampleMapper.selectAll();
        return WsResult.success("成功了", data);
    }

    public JSONArray getDattributes(String genes) {
        String str = genes.toUpperCase();
        byte[] bArray = HexStringToBinary(str);
        String binaryStr = bytes2BinaryStr(bArray);
        int body = getMainBody(binaryStr);
        int pattern = getMainPattern(binaryStr);
        int eyetype = getMainEyeType(binaryStr);
        int bodycolor = getMainBodyColor(binaryStr);
        int petcolor = getMainPatColor(binaryStr);
        int wild = getMainWild(binaryStr);
        int mouth = getMainMouth(binaryStr);
        JSONObject object = new JSONObject();
        JSONArray dattributes = new JSONArray();
        String bodyGenes = GENES_BODY[body];
        object.put("body", bodyGenes);
        object.put("imageurl", "body.png");
        dattributes.add(object);
        String mouthGenes = GENES_MOUTH[mouth];
        object = new JSONObject();
        object.put("mouth", mouthGenes);
        object.put("imageurl", "mouth.png");
        dattributes.add(object);
        String patternGenes = GENES_PATTERN[pattern];
        object = new JSONObject();
        object.put("pattern", patternGenes);
        object.put("imageurl", "pattern.png");
        dattributes.add(object);

        String wildGenes = GENES_WILD[wild];

        object = new JSONObject();
        object.put("wild", wildGenes);
        object.put("imageurl", "pattern.png");
        dattributes.add(object);

        String eyetypeGenes = GENES_EYETYPE[eyetype];

        object = new JSONObject();
        object.put("eyetype", eyetypeGenes);
        object.put("imageurl", "eyetype.png");
        dattributes.add(object);

        String bodycolorGenes = GENES_BODECOLOR[bodycolor];

        object = new JSONObject();
        object.put("bodycolor", bodycolorGenes);
        object.put("imageurl", "bodycolor.png");
        dattributes.add(object);

        String patcolorGenes = GENES_PATCOLOR[petcolor];
        object.put("patterncolor", patcolorGenes);
        object.put("imageurl", "patcolor.png");
        dattributes.add(object);
        return dattributes;
    }

    @RequestMapping(value = "/mixGenes.do", produces = { MediaType.APPLICATION_JSON_VALUE })
    @ResponseBody
    public Object mixGenes(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String matronId = request.getParameter("matronId");
        String sireId = request.getParameter("sireId");
        String str = matronId.toUpperCase();
        byte[] bArray = HexStringToBinary(str);

        String binaryStr = bytes2BinaryStr(bArray);

        int[] matronIdKai = binaryToKai48(binaryStr);

        str = sireId.toUpperCase();
        bArray = HexStringToBinary(str);

        binaryStr = bytes2BinaryStr(bArray);
        int[] sireIdKai = binaryToKai48(binaryStr);
        int[] babyKai = new int[48];
        // PARENT GENE SWAPPING
        for (int i = 0; i < 12; i++) {
            int index = 4 * i;
            for (int j = 3; j > 0; j--) {
                if (Math.random() < 0.25) {
                    swap(matronIdKai, index + j, index + j - 1);
                }
                if (Math.random() < 0.25) {
                    swap(sireIdKai, index + j, index + j - 1);
                }
            }
        }

        // BABY GENES

        for (int i = 0; i < 48; i++) {
            int mutation = 0;
            // CHECK MUTATION
            if (i % 4 == 0) {
                int gene1 = matronIdKai[i];
                int gene2 = sireIdKai[i];
                if (gene1 > gene2) {
                    int temp = gene1;
                    gene1 = gene2;
                    gene2 = temp;
                }
                if ((gene2 - gene1) == 1 && (gene1 % 2) == 0) {
                    float probability = 0.25f;
                    if (gene1 > 23) {
                        probability /= 2;
                    }
                    if (Math.random() < probability) {
                        mutation = (gene1 / 2) + 16;
                    }
                }
            }

            // GIVE BABY GENES
            if (mutation > 0) {
                babyKai[i] = mutation;
            } else {
                if (Math.random() < 0.5) {
                    babyKai[i] = matronIdKai[i];
                } else {
                    babyKai[i] = sireIdKai[i];
                }
            }
        }
        String currentPath = Tools.currentPath(request);
        String filePath = currentPath + "testimage/";
        createDir(filePath);

        File file = new File(filePath);
        File[] listfile = file.listFiles();
        String kittyID = "" + (listfile.length + 1);

        String SvgFilePath = filePath + kittyID + ".svg";

        int body = babyKai[47];
        int pattern = babyKai[43];
        int eyecolor = babyKai[39];
        int eyetype = babyKai[35];
        int bodycolor = babyKai[31];
        int petcolor = babyKai[27];
        int secondColor = babyKai[23];
        int wild = babyKai[19];
        int mouth = babyKai[15];
        int[] kaiGenes = { body, pattern, eyecolor, eyetype, bodycolor, petcolor, secondColor, wild, mouth };
        createKittyForKai(request, kaiGenes, kittyID, SvgFilePath);
        String hexString = binaryString2hexString(binaryStr);
        String newGenes = hexString;
        JSONObject object = new JSONObject();
        object.put("babygenes", newGenes);

        return WsResult.success("OK", object);

    }

    public void swap(int[] genes, int index1, int index2) {
        int temp = genes[index1];
        genes[index1] = genes[index2];
        genes[index2] = temp;
    }

    private int[] binaryToKai48(String binaryStr) {
        int[] kaiGenes = new int[48];
        int length = binaryStr.length();
        if (length == 256) {
            int index = length - 1;
            for (int i = 0; i < 48; i++) {
                int currentKai = index - i * 5;
                kaiGenes[47 - i] = getDominant(binaryStr, currentKai);
            }
        }

        return kaiGenes;

    }

    private void genes0Special48(HttpServletRequest request) {

        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "cattributes.json";
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                cattributesObject = JSONObject.parseObject(input);

            } catch (Exception e) {
                e.printStackTrace();
                cattributesObject = null;
            }
        }

        JSONObject object = new JSONObject();

        JSONObject jsonObject = cattributesObject;

        if (jsonObject != null) {
            // if(bodys!=null) {
            JSONArray bodys = jsonObject.getJSONArray("body");
            JSONArray eyecolors = jsonObject.getJSONArray("eyecolor");
            JSONArray eyetypes = jsonObject.getJSONArray("eyetype");
            JSONArray pattrens = jsonObject.getJSONArray("pattern");
            JSONArray bodycolor = jsonObject.getJSONArray("bodycolor");
            JSONArray patcolor = jsonObject.getJSONArray("patcolor");
            JSONArray pupilcolor = jsonObject.getJSONArray("pupilcolor");
            JSONArray mouths = jsonObject.getJSONArray("mouth");
            JSONArray wild = jsonObject.getJSONArray("wild");
            int eyecolorcount = eyecolors.size();

            int currentDog = 98;
            for (int i = 0; i < 30; i++) {

                bodys = jsonObject.getJSONArray("body");
                JSONObject bodyGenes = null;
                int index = currentDog % 10;
                bodyGenes = bodys.getJSONObject(index);
                String bodyvalue = bodyGenes.getString("name");

                // pattren
                index = 13 + currentDog % 5;
                JSONObject pattrenGenes = pattrens.getJSONObject(index/* patCount-1-i */);
                String patternvalue = pattrenGenes.getString("name");

                // bodycolor
                index = 10 + currentDog % 4;
                JSONObject bodycolorGenes = bodycolor.getJSONObject(index);
                String bodycolorvalue = bodycolorGenes.getString("name");

                // pattercolor
                index = 10 + currentDog % 4;
                JSONObject patcolorGenes = patcolor.getJSONObject(index/* patSize-1-i *//* l */);
                String patcolorvalue = patcolorGenes.getString("name");
                index = currentDog % eyecolorcount;
                JSONObject eyecolorGenes = eyecolors.getJSONObject(index);
                String eyecolorvalue = eyecolorGenes.getString("name");
                int eyetypecount = eyetypes.size();
                index = currentDog % eyetypecount;

                JSONObject eyetypesGenes = eyetypes.getJSONObject(index);
                String eyetypevalue = eyetypesGenes.getString("name");
                boolean ishaveBKG = false;
                index = currentDog % 2;
                ishaveBKG = true;

                JSONObject pupilGenes = pupilcolor.getJSONObject(index);
                String pupilvalue = pupilGenes.getString("name");
                int mouthscount = mouths.size();
                index = currentDog % mouthscount;
                JSONObject mouthsGenes = mouths.getJSONObject(index);
                String mouthvalue = mouthsGenes.getString("name");

                boolean haveCloth = false;
                index = currentDog % 3;
                if (index < 2) {
                    haveCloth = true;
                }
                index = 1 + currentDog % 2;
                haveCloth = true;

                JSONObject wildGenes = wild.getJSONObject(index);
                String wildvalue = wildGenes.getString("name");
                int[] genes = new int[48];

                setMutateGenes(bodyvalue, GENES_BODY, genes, 47);

                setMutateGenes(patternvalue, GENES_PATTERN, genes, 43);
                // eyecolor
                setGenes(eyecolorvalue, GENES_EYECOLOR, genes, 39, 1);
                randomGenes(eyecolors, 3, GENES_EYECOLOR, genes, 38);
                // eyetype
                setGenes(eyetypevalue, GENES_EYETYPE, genes, 35, 1);
                randomGenes(eyetypes, 3, GENES_EYETYPE, genes, 34);
                // BODY COLOR
                setMutateGenes(bodycolorvalue, GENES_BODECOLOR, genes, 31);
                // PAT COLOR
                setMutateGenes(patcolorvalue, GENES_PATCOLOR, genes, 27);
                // SEC COLOR
                if (ishaveBKG) {
                    setGenes(pupilvalue, GENES_SECONDCOLOR, genes, 23, 1);
                    for (int s = 0; s < 3; s++) {
                        genes[22 - s] = 5;
                    }
                } else {
                    for (int s = 0; s < 4; s++) {
                        genes[23 - s] = 5;
                    }
                }

                // SEC COLOR
                if (haveCloth) {
                    setGenes(wildvalue, GENES_WILD, genes, 19, 1);
                    for (int s = 0; s < 3; s++) {
                        genes[18 - s] = 1;
                    }
                } else {
                    for (int s = 0; s < 4; s++) {
                        genes[19 - s] = 1;
                    }
                }
                // mouth
                setGenes(mouthvalue, GENES_MOUTH, genes, 15, 1);
                randomGenes(mouths, 3, GENES_MOUTH, genes, 14);

                mouthsGenes = mouths.getJSONObject(1);
                mouthvalue = mouthsGenes.getString("name");
                setGenes(mouthvalue, GENES_MOUTH, genes, 11, 4);
                setGenes(mouthvalue, GENES_MOUTH, genes, 7, 4);
                setGenes(mouthvalue, GENES_MOUTH, genes, 3, 4);
                String binaryStr = "";
                for (int m = 0; m < 48; m++) {
                    binaryStr += toBinaryString(genes[m]);
                }
                String newGenes = "0000" + binaryString2hexString(binaryStr);
                createKittyByGenes(request, newGenes, "" + currentDog);
                BigInteger bigInt = new BigInteger(newGenes, 16);
                System.err.println("BigInteger" + bigInt.toString(10));
                object.put("kitty" + currentDog, newGenes);
                currentDog++;
            }
        }

        String currentPath = Tools.currentPath(request);
        String filePath = currentPath + "image/gene.json";
        try {
            writeFile(filePath, object.toString());
            System.out.println("genes！" + object.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    void setMutateGenes(String currentGenes, String[] constGenes, int[] newGenes, int newGenesIndex) {
        Random ran1 = new Random(4);
        int boyGenesIndex = getGenes(currentGenes, constGenes);
        // 设置基因
        if (boyGenesIndex <= 15) {// 基本的层，
            setGenes(currentGenes, constGenes, newGenes, newGenesIndex, 4);
        } else {//
            setGenes(currentGenes, constGenes, newGenes, newGenesIndex, 1);

            for (int s = 0; s < 3; s++) {
                int rand = ran1.nextInt(10000) % 2;
                newGenes[newGenesIndex - 1 - s] = (boyGenesIndex - 16) * 2 + rand;
            }
        }
    }

    void setGenes(String currentGenes, String[] constGenes, int[] newGenes, int newGenesIndex, int count) {
        int currentGenesIndex = 0;
        boolean isfind = false;
        for (int j = 0; j < constGenes.length; j++) {
            if (constGenes[j].equals(currentGenes)) {
                currentGenesIndex = j;
                isfind = true;
                break;
            }
        }
        if (!isfind) {
        }
        for (int i = 0; i < count; i++) {
            newGenes[newGenesIndex - i] = currentGenesIndex;
        }
    }

    int getGenes(String currentGenes, String[] constGenes) {
        int currentGenesIndex = 0;

        for (int j = 0; j < constGenes.length; j++) {
            if (constGenes[j].equals(currentGenes)) {
                currentGenesIndex = j;
                break;
            }
        }
        return currentGenesIndex;

    }

    public String siringDog(HttpServletRequest request, int mid, int sid, String matronId, String sireId,
            JSONObject baby) throws InterruptedException {

        String str = matronId.toUpperCase();
        byte[] bArray = HexStringToBinary(str);

        String binaryStr = bytes2BinaryStr(bArray);

        int[] matronIdKai = binaryToKai48(binaryStr);

        str = sireId.toUpperCase();
        bArray = HexStringToBinary(str);

        binaryStr = bytes2BinaryStr(bArray);
        int[] sireIdKai = binaryToKai48(binaryStr);
        int[] babyKai = new int[48];
        Random ran1 = new Random(4);
        // PARENT GENE SWAPPING
        for (int i = 0; i < 12; i++) {
            int index = 4 * i;
            for (int j = 3; j > 0; j--) {
                Thread.sleep(10);
                int rand = ran1.nextInt(10000) % 4;
                baby.put("rand1" + i + "=", rand);
                if (rand < 1) {
                    swap(matronIdKai, index + j, index + j - 1);
                }
                Thread.sleep(10);
                rand = ran1.nextInt(10000) % 4;
                baby.put("rand2" + i + "=", rand);
                if (rand < 1) {
                    swap(sireIdKai, index + j, index + j - 1);
                }
            }
        }

        // BABY GENES

        for (int i = 0; i < 48; i++) {
            int mutation = 0;
            // CHECK MUTATION
            if (i % 4 == 0) {
                int gene1 = matronIdKai[47 - i];
                int gene2 = sireIdKai[47 - i];
                if (gene1 > gene2) {
                    int temp = gene1;
                    gene1 = gene2;
                    gene2 = temp;
                }
                if ((gene2 - gene1) == 1 && (gene1 % 2) == 0) {
                    Thread.sleep(10);
                    int rand = ran1.nextInt(10000) % 4;
                    baby.put("rand3" + i + "=", rand);
                    if (rand < 1) {
                        mutation = (gene1 / 2) + 16;
                    }
                }
            }

            // GIVE BABY GENES
            if (mutation > 0) {
                baby.put("mutation" + i + "=", mutation);
                babyKai[47 - i] = mutation;
            } else {
                Thread.sleep(10);
                int rand = ran1.nextInt(10000) % 4;
                System.out.println("rand4" + i + "=" + rand);
                baby.put("rand4*" + i + "=", rand);
                if (rand < 2) {
                    babyKai[47 - i] = matronIdKai[47 - i];
                } else {
                    babyKai[47 - i] = sireIdKai[47 - i];
                }
            }
        }
        baby.put("matronIdKai=", matronIdKai);
        baby.put("sireIdKai=", sireIdKai);
        baby.put("babyKai=", babyKai);
        String currentPath = Tools.currentPath(request);
        String filePath = currentPath + "image/child2/";
        createDir(filePath);

        String kittyID = "" + mid + "+" + sid;

        String SvgFilePath = filePath + kittyID + ".svg";

        int body = babyKai[47];
        int pattern = babyKai[43];
        int eyecolor = babyKai[39];
        int eyetype = babyKai[35];
        int bodycolor = babyKai[31];
        int petcolor = babyKai[27];
        int secondColor = babyKai[23];
        int wild = babyKai[19];
        int mouth = babyKai[15];
        int[] kaiGenes = { body, pattern, eyecolor, eyetype, bodycolor, petcolor, secondColor, wild, mouth };
        createKittyForKai(request, kaiGenes, kittyID, SvgFilePath);
        String binaryStr1 = "";
        for (int m = 0; m < 48; m++) {
            binaryStr1 += toBinaryString(babyKai[m]);
        }
        String hexString = binaryString2hexString(binaryStr1);
        String newGenes = "0000" + hexString;
        return newGenes;
    }

    public void lowgenesCreate(HttpServletRequest request) {
        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "cattributes.json";
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                cattributesObject = JSONObject.parseObject(input);
            } catch (Exception e) {
                e.printStackTrace();
                cattributesObject = null;
            }
        }

        JSONObject object = new JSONObject(true);
        String allGensStrings = "";

        JSONObject jsonObject = cattributesObject;

        if (jsonObject != null) {
            JSONArray bodys = jsonObject.getJSONArray("body");
            JSONArray eyecolors = jsonObject.getJSONArray("eyecolor");
            JSONArray eyetypes = jsonObject.getJSONArray("eyetype");
            JSONArray pattrens = jsonObject.getJSONArray("pattern");
            JSONArray bodycolor = jsonObject.getJSONArray("bodycolor");
            JSONArray patcolor = jsonObject.getJSONArray("patcolor");
            JSONArray pupilcolor = jsonObject.getJSONArray("pupilcolor");
            JSONArray mouths = jsonObject.getJSONArray("mouth");
            JSONArray wild = jsonObject.getJSONArray("wild");

            int currentDog = 0;
            for (int i = 1; i < 7; i++) {

                bodys = jsonObject.getJSONArray("body");
                JSONObject bodyGenes = null;

                int index = i;// currentDog%7;
                bodyGenes = bodys.getJSONObject(index);
                bodyGenes = bodys.getJSONObject(index);
                String bodyvalue = bodyGenes.getString("name");

                // pattren
                for (int j = 0; j < 14; j++) {
                    index = currentDog % 10;
                    JSONObject pattrenGenes = pattrens.getJSONObject(j);
                    String patternvalue = pattrenGenes.getString("name");
                    // bodycolor
                    for (int k = 0; k < 10; k++) {
                        index = currentDog % 10;
                        JSONObject bodycolorGenes = bodycolor.getJSONObject(k);
                        String bodycolorvalue = bodycolorGenes.getString("name");
                        // pattercolor
                        for (int l = 0; l < 1; l++) {
                            index = currentDog % 10;
                            // JSONObject patcolorGenes = patcolor.getJSONObject(index/*patSize-1-i*//*l*/);
                            JSONObject patcolorGenes = patcolor.getJSONObject(l);
                            String patcolorvalue = patcolorGenes.getString("name");
                            index = currentDog % 2;
                            JSONObject eyecolorGenes = eyecolors.getJSONObject(index);
                            String eyecolorvalue = eyecolorGenes.getString("name");
                            index = currentDog % 2;

                            JSONObject eyetypesGenes = eyetypes.getJSONObject(index);
                            String eyetypevalue = eyetypesGenes.getString("name");
                            boolean ishaveBKG = false;
                            JSONObject pupilGenes = pupilcolor.getJSONObject(index);
                            String pupilvalue = pupilGenes.getString("name");
                            index = currentDog % 3;
                            JSONObject mouthsGenes = mouths.getJSONObject(index);
                            String mouthvalue = mouthsGenes.getString("name");

                            boolean haveCloth = false;
                            index = 0;
                            JSONObject wildGenes = wild.getJSONObject(index);
                            String wildvalue = wildGenes.getString("name");
                            int[] genes = new int[48];
                            setMutateGenes(bodyvalue, GENES_BODY, genes, 47);
                            setMutateGenes(patternvalue, GENES_PATTERN, genes, 43);
                            // eyecolor
                            setGenes(eyecolorvalue, GENES_EYECOLOR, genes, 39, 1);
                            randomGenes(eyecolors, 3, GENES_EYECOLOR, genes, 38);
                            // eyetype
                            setGenes(eyetypevalue, GENES_EYETYPE, genes, 35, 1);
                            randomGenes(eyetypes, 3, GENES_EYETYPE, genes, 34);
                            // BODY COLOR
                            setMutateGenes(bodycolorvalue, GENES_BODECOLOR, genes, 31);
                            // PAT COLOR
                            setMutateGenes(patcolorvalue, GENES_PATCOLOR, genes, 27);
                            // SEC COLOR
                            if (ishaveBKG) {
                                setGenes(pupilvalue, GENES_SECONDCOLOR, genes, 23, 1);
                                // randomGenes(pupilcolor, 3, GENES_SECONDCOLOR, genes, 22);
                                for (int s = 0; s < 3; s++) {
                                    genes[22 - s] = 5;
                                }
                            } else {
                                for (int s = 0; s < 4; s++) {
                                    genes[23 - s] = 5;
                                }
                            }

                            // SEC COLOR
                            if (haveCloth) {
                                setGenes(wildvalue, GENES_WILD, genes, 19, 1);
                                // randomGenes(wild, 3, GENES_WILD, genes, 18);
                                for (int s = 0; s < 3; s++) {
                                    genes[18 - s] = 1;
                                }
                            } else {
                                for (int s = 0; s < 4; s++) {
                                    genes[19 - s] = 1;
                                }
                            }
                            // mouth
                            setGenes(mouthvalue, GENES_MOUTH, genes, 15, 1);
                            randomGenes(mouths, 3, GENES_MOUTH, genes, 14);

                            mouthsGenes = mouths.getJSONObject(1);
                            mouthvalue = mouthsGenes.getString("name");
                            setGenes(mouthvalue, GENES_MOUTH, genes, 11, 4);
                            setGenes(mouthvalue, GENES_MOUTH, genes, 7, 4);
                            setGenes(mouthvalue, GENES_MOUTH, genes, 3, 4);
                            // System.out.println("genes！" + genes);
                            String binaryStr = "";
                            for (int m = 0; m < 48; m++) {
                                binaryStr += toBinaryString(genes[m]);
                            }
                            String newGenes = "0000" + binaryString2hexString(binaryStr);
                            createKittyByGenes(request, newGenes, "" + currentDog);
                            BigInteger bigInt = new BigInteger(newGenes, 16);
                            System.err.println("BigInteger" + bigInt.toString(10));
                            object.put("" + currentDog, newGenes);
                            allGensStrings += "Kitty" + currentDog + " Genes:" + newGenes + "\r\n";
                            currentDog++;
                        }
                    }
                }
            }
        }

        String currentPath = Tools.currentPath(request);
        String filePath = currentPath + "image/gene.json";
        try {
            writeFile(filePath, allGensStrings);
            System.out.println("genes！" + object.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createDogs(HttpServletRequest request) {
        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "prasale.json";
            JSONArray saleArray = null;
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                saleArray = JSONObject.parseArray(input);

            } catch (Exception e) {
                e.printStackTrace();
                saleArray = null;
            }
            JSONObject object = new JSONObject();

            for (int i = 0; i < saleArray.size(); i++) {
                JSONObject saleInfo = saleArray.getJSONObject(i);
                String walletAddress = saleInfo.getString("address");
                JSONArray genesArray = saleInfo.getJSONArray("genes");
                for (int j = 0; j < genesArray.size(); j++) {
                    String genes = genesArray.getString(j);
                    String url = "http://49.51.36.172:821/block/createPromoPup?genes=" + genes + "&owner="
                            + walletAddress;
                    String result = sendGet(url, null);
                    System.out.println("result！" + result);
                    object.put("walletAddress:" + walletAddress + ":genes" + genes, result);

                }
            }

            String filePath = currentPath + "result.json";
            try {
                writeFile(filePath, object.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url /* + "?" + param */;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public void genesPromoPup(HttpServletRequest request) {

        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "cattributes.json";
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                cattributesObject = JSONObject.parseObject(input);

            } catch (Exception e) {
                e.printStackTrace();
                cattributesObject = null;
            }
        }

        JSONObject object = new JSONObject();

        JSONObject jsonObject = cattributesObject;

        if (jsonObject != null) {
            JSONArray bodys = jsonObject.getJSONArray("body");
            JSONArray eyecolors = jsonObject.getJSONArray("eyecolor");
            JSONArray eyetypes = jsonObject.getJSONArray("eyetype");
            JSONArray pattrens = jsonObject.getJSONArray("pattern");
            JSONArray bodycolor = jsonObject.getJSONArray("bodycolor");
            JSONArray patcolor = jsonObject.getJSONArray("patcolor");
            JSONArray pupilcolor = jsonObject.getJSONArray("pupilcolor");
            JSONArray mouths = jsonObject.getJSONArray("mouth");
            JSONArray wild = jsonObject.getJSONArray("wild");
            int eyecolorcount = eyecolors.size();

            int currentDog = 0;
            for (int i = 0; i < 100; i++) {

                bodys = jsonObject.getJSONArray("body");
                JSONObject bodyGenes = null;
                int index = currentDog % 6;
                bodyGenes = bodys.getJSONObject(index);
                String bodyvalue = bodyGenes.getString("name");

                // pattren
                int patCount = pattrens.size();
                index = patCount - 4 + currentDog % 3;
                JSONObject pattrenGenes = pattrens.getJSONObject(index/* patCount-1-i */);
                String patternvalue = pattrenGenes.getString("name");

                // bodycolor
                index = 10 + currentDog % 4;
                JSONObject bodycolorGenes = bodycolor.getJSONObject(index/* colorcount-1-i */);
                String bodycolorvalue = bodycolorGenes.getString("name");

                // pattercolor
                index = 6 + currentDog % 4;
                JSONObject patcolorGenes = patcolor.getJSONObject(index/* patSize-1-i *//* l */);
                String patcolorvalue = patcolorGenes.getString("name");
                index = currentDog % eyecolorcount;
                JSONObject eyecolorGenes = eyecolors.getJSONObject(index);
                String eyecolorvalue = eyecolorGenes.getString("name");
                int eyetypecount = eyetypes.size();
                index = currentDog % eyetypecount;

                JSONObject eyetypesGenes = eyetypes.getJSONObject(index);
                String eyetypevalue = eyetypesGenes.getString("name");
                boolean ishaveBKG = false;
                if (i < 7) {
                    index = currentDog % 2;
                    ishaveBKG = true;
                } else {
                    index = 0;
                }

                JSONObject pupilGenes = pupilcolor.getJSONObject(index);
                String pupilvalue = pupilGenes.getString("name");
                int mouthscount = mouths.size();
                index = currentDog % mouthscount;
                JSONObject mouthsGenes = mouths.getJSONObject(index);
                String mouthvalue = mouthsGenes.getString("name");

                boolean haveCloth = false;
                if (i < 7) {
                    index = 1 + currentDog % 2;
                    haveCloth = true;
                } else {
                    index = currentDog % 3;
                    if (index < 2) {
                        haveCloth = true;
                    }
                }
                JSONObject wildGenes = wild.getJSONObject(index);
                String wildvalue = wildGenes.getString("name");
                int[] genes = new int[48];
                setMutateGenes(bodyvalue, GENES_BODY, genes, 47);

                setMutateGenes(patternvalue, GENES_PATTERN, genes, 43);
                // eyecolor
                setGenes(eyecolorvalue, GENES_EYECOLOR, genes, 39, 1);
                randomGenes(eyecolors, 3, GENES_EYECOLOR, genes, 38);
                // eyetype
                setGenes(eyetypevalue, GENES_EYETYPE, genes, 35, 1);
                randomGenes(eyetypes, 3, GENES_EYETYPE, genes, 34);
                // BODY COLOR
                setMutateGenes(bodycolorvalue, GENES_BODECOLOR, genes, 31);
                // PAT COLOR
                setMutateGenes(patcolorvalue, GENES_PATCOLOR, genes, 27);
                // SEC COLOR
                if (ishaveBKG) {
                    setGenes(pupilvalue, GENES_SECONDCOLOR, genes, 23, 1);
                    for (int s = 0; s < 3; s++) {
                        genes[22 - s] = 5;
                    }
                } else {
                    for (int s = 0; s < 4; s++) {
                        genes[23 - s] = 5;
                    }
                }

                // SEC COLOR
                if (haveCloth) {
                    setGenes(wildvalue, GENES_WILD, genes, 19, 1);
                    // randomGenes(wild, 3, GENES_WILD, genes, 18);
                    for (int s = 0; s < 3; s++) {
                        genes[18 - s] = 1;
                    }
                } else {
                    for (int s = 0; s < 4; s++) {
                        genes[19 - s] = 1;
                    }
                }
                // mouth
                setGenes(mouthvalue, GENES_MOUTH, genes, 15, 1);
                randomGenes(mouths, 3, GENES_MOUTH, genes, 14);

                mouthsGenes = mouths.getJSONObject(1);
                mouthvalue = mouthsGenes.getString("name");
                setGenes(mouthvalue, GENES_MOUTH, genes, 11, 4);
                setGenes(mouthvalue, GENES_MOUTH, genes, 7, 4);
                setGenes(mouthvalue, GENES_MOUTH, genes, 3, 4);
                // System.out.println("genes！" + genes);
                String binaryStr = "";
                for (int m = 0; m < 48; m++) {
                    binaryStr += toBinaryString(genes[m]);
                }
                String newGenes = "0000" + binaryString2hexString(binaryStr);
                createKittyByGenes(request, newGenes, "" + currentDog);
                BigInteger bigInt = new BigInteger(newGenes, 16);
                System.err.println("BigInteger" + bigInt.toString(10));
                object.put("kitty" + currentDog, newGenes);
                object.put("kittyKai" + currentDog, genes);
                object.put("BigInteger" + currentDog, bigInt.toString(10));
                currentDog++;
            }
        }

        String currentPath = Tools.currentPath(request);
        String filePath = currentPath + "image/gene.json";
        try {
            writeFile(filePath, object.toString());
            System.out.println("genes！" + object.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void createVipDogs(HttpServletRequest request) {

        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "cattributes.json";
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                cattributesObject = JSONObject.parseObject(input);

            } catch (Exception e) {
                e.printStackTrace();
                cattributesObject = null;
            }
        }

        JSONObject object = new JSONObject();

        JSONObject jsonObject = cattributesObject;

        if (jsonObject != null) {
            JSONArray bodys = jsonObject.getJSONArray("body");
            JSONArray eyecolors = jsonObject.getJSONArray("eyecolor");
            JSONArray eyetypes = jsonObject.getJSONArray("eyetype");
            JSONArray pattrens = jsonObject.getJSONArray("pattern");
            JSONArray bodycolor = jsonObject.getJSONArray("bodycolor");
            JSONArray patcolor = jsonObject.getJSONArray("patcolor");
            JSONArray pupilcolor = jsonObject.getJSONArray("pupilcolor");
            JSONArray mouths = jsonObject.getJSONArray("mouth");
            JSONArray wild = jsonObject.getJSONArray("wild");
            int count = bodys.size();
            int currentDog = 0;
            Random ran1 = new Random(4);
            for (int i = 0; i < count; i++) {

                bodys = jsonObject.getJSONArray("body");
                int bodysize = bodys.size();
                JSONObject bodyGenes = null;
                int rand = 0;
                int index = rand;// L2, L3
                int bodyIndex = i;// index;
                bodyGenes = bodys.getJSONObject(bodyIndex);
                String bodyvalue = bodyGenes.getString("name");
                // pattren
                for (int j = 0; j < 1; j++) {
                    int patCount = pattrens.size();
                    rand = ran1.nextInt(10000) % 7;
                    // index = 7;//L2
                    boolean isFindPat = false;
                    int patIndex = 0;
                    for (int mm = 0; mm < patCount; mm++) {

                        JSONObject pattern = pattrens.getJSONObject(mm);
                        String patName = pattern.getString("name");
                        String curBodyvalue = bodyvalue;
                        if (i == bodysize - 1) {
                            curBodyvalue = "bankuaishengji";
                        }
                        if (curBodyvalue.equals("bianmu")) {
                            if (patName.equals("bianmuhuawen")) {
                                isFindPat = true;
                                patIndex = mm;
                                break;
                            }
                        } else {
                            if (patName.equals(curBodyvalue)) {
                                isFindPat = true;
                                patIndex = mm;
                                break;
                            }
                        }
                    }
                    JSONObject pattrenGenes = pattrens.getJSONObject(patIndex/* patCount-1-i */);

                    String patternvalue = pattrenGenes.getString("name");

                    // bodycolor
                    int colorcount = bodycolor.size();
                    rand = ran1.nextInt(10000) % 4;
                    index = colorcount - 1;// currentDog%colorcount;//L2
                    JSONObject bodycolorGenes = bodycolor.getJSONObject(index/* colorcount-1-i */);

                    String bodycolorvalue = bodycolorGenes.getString("name");

                    // pattercolor
                    int patSize = patcolor.size();
                    rand = ran1.nextInt(10000) % 5;
                    index = patSize - 1;// colorcount/patSize;

                    JSONObject patcolorGenes = patcolor.getJSONObject(index/* patSize-1-i *//* l */);
                    String patcolorvalue = patcolorGenes.getString("name");
                    rand = ran1.nextInt(10000);
                    int eyecolorSize = eyecolors.size();
                    index = eyecolorSize - 1;// currentDog%eyecolorSize;

                    JSONObject eyecolorGenes = eyecolors.getJSONObject(index);
                    String eyecolorvalue = eyecolorGenes.getString("name");
                    int eyetypecount = eyetypes.size();
                    // rand = eyetypecount;
                    index = currentDog % eyetypecount;

                    JSONObject eyetypesGenes = eyetypes.getJSONObject(index);
                    String eyetypevalue = eyetypesGenes.getString("name");
                    boolean ishaveBKG = false;
                    index = 0;
                    JSONObject pupilGenes = pupilcolor.getJSONObject(index);
                    String pupilvalue = pupilGenes.getString("name");
                    rand = ran1.nextInt(10000);
                    index = 0;// rand%mouthscount;
                    JSONObject mouthsGenes = mouths.getJSONObject(index);
                    String mouthvalue = mouthsGenes.getString("name");

                    int wildcount = wild.size();
                    boolean haveCloth = false;

                    index = wildcount - 1;
                    haveCloth = true;
                    JSONObject wildGenes = wild.getJSONObject(index);
                    String wildvalue = wildGenes.getString("name");
                    int[] genes = new int[48];

                    setMutateGenes(bodyvalue, GENES_BODY, genes, 47);
                    if (isFindPat) {
                        setMutateGenes(patternvalue, GENES_PATTERN, genes, 43);
                    } else {
                        for (int s = 0; s < 4; s++) {
                            genes[43 - s] = 1;
                        }
                    }

                    // eyecolor
                    setGenes(eyecolorvalue, GENES_EYECOLOR, genes, 39, 1);
                    randomGenes(eyecolors, 3, GENES_EYECOLOR, genes, 38);
                    // eyetype
                    setGenes(eyetypevalue, GENES_EYETYPE, genes, 35, 1);
                    randomGenes(eyetypes, 3, GENES_EYETYPE, genes, 34);
                    // BODY COLOR
                    setMutateGenes(bodycolorvalue, GENES_BODECOLOR, genes, 31);
                    // PAT COLOR
                    setMutateGenes(patcolorvalue, GENES_PATCOLOR, genes, 27);
                    // SEC COLOR
                    if (ishaveBKG) {
                        setGenes(pupilvalue, GENES_SECONDCOLOR, genes, 23, 1);
                        for (int s = 0; s < 3; s++) {
                            genes[22 - s] = 5;
                        }
                    } else {
                        for (int s = 0; s < 4; s++) {
                            genes[23 - s] = 5;
                        }
                    }

                    // SEC COLOR
                    if (haveCloth) {
                        setGenes(wildvalue, GENES_WILD, genes, 19, 1);
                        // randomGenes(wild, 3, GENES_WILD, genes, 18);
                        for (int s = 0; s < 3; s++) {
                            genes[18 - s] = 1;
                        }
                    } else {
                        for (int s = 0; s < 4; s++) {
                            genes[19 - s] = 1;
                        }
                    }
                    // mouth
                    setGenes(mouthvalue, GENES_MOUTH, genes, 15, 1);
                    randomGenes(mouths, 3, GENES_MOUTH, genes, 14);

                    mouthsGenes = mouths.getJSONObject(1);
                    mouthvalue = mouthsGenes.getString("name");
                    setGenes(mouthvalue, GENES_MOUTH, genes, 11, 4);
                    setGenes(mouthvalue, GENES_MOUTH, genes, 7, 4);
                    setGenes(mouthvalue, GENES_MOUTH, genes, 3, 4);
                    String binaryStr = "";
                    for (int m = 0; m < 48; m++) {
                        binaryStr += toBinaryString(genes[m]);
                    }
                    String newGenes = "0000" + binaryString2hexString(binaryStr);
                    createKittyByGenes(request, newGenes, "" + currentDog);
                    BigInteger bigInt = new BigInteger(newGenes, 16);
                    System.err.println("BigInteger" + bigInt.toString(10));
                    object.put("kitty" + currentDog, newGenes);
                    object.put("kittyKai" + currentDog, genes);
                    currentDog++;
                }
            }
        }

        String currentPath = Tools.currentPath(request);
        String filePath = currentPath + "image/gene.json";
        try {
            writeFile(filePath, object.toString());
            System.out.println("genes！" + object.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void lowgenesCreateBylow(HttpServletRequest request) {
        if (cattributesObject == null) {
            String currentPath = Tools.currentPath(request);
            String cattributesPath = currentPath + "resource/" + "cattributes.json";
            try {
                String input = FileUtils.readFileToString(new File(cattributesPath), "UTF-8");
                cattributesObject = JSONObject.parseObject(input);

            } catch (Exception e) {
                e.printStackTrace();
                cattributesObject = null;
            }
        }

        JSONObject object = new JSONObject(true);
        String allGensStrings = "";

        JSONObject jsonObject = cattributesObject;

        if (jsonObject != null) {
            JSONArray bodys = jsonObject.getJSONArray("body");
            JSONArray eyecolors = jsonObject.getJSONArray("eyecolor");
            JSONArray eyetypes = jsonObject.getJSONArray("eyetype");
            JSONArray pattrens = jsonObject.getJSONArray("pattern");
            JSONArray bodycolor = jsonObject.getJSONArray("bodycolor");
            JSONArray patcolor = jsonObject.getJSONArray("patcolor");
            JSONArray pupilcolor = jsonObject.getJSONArray("pupilcolor");
            JSONArray mouths = jsonObject.getJSONArray("mouth");
            JSONArray wild = jsonObject.getJSONArray("wild");

            int currentDog = 0;
            for (int i = 1; i < 4; i++) {
                int index = currentDog % 10;
                JSONObject patcolorGenes = patcolor.getJSONObject(i);
                String patcolorvalue = patcolorGenes.getString("name");

                // pattren
                for (int j = 0; j < 6; j++) {

                    index = currentDog % 10;
                    JSONObject bodycolorGenes = bodycolor.getJSONObject(j);
                    String bodycolorvalue = bodycolorGenes.getString("name");

                    // bodycolor
                    for (int k = 0; k < 6; k++) {

                        index = currentDog % 10;
                        JSONObject pattrenGenes = pattrens.getJSONObject(k);
                        String patternvalue = pattrenGenes.getString("name");

                        for (int l = 0; l < 7; l++) {
                            bodys = jsonObject.getJSONArray("body");
                            JSONObject bodyGenes = null;
                            index = l;// currentDog%7;
                            bodyGenes = bodys.getJSONObject(index);
                            bodyGenes = bodys.getJSONObject(index);
                            String bodyvalue = bodyGenes.getString("name");
                            index = currentDog % 2;
                            JSONObject eyecolorGenes = eyecolors.getJSONObject(index);
                            String eyecolorvalue = eyecolorGenes.getString("name");
                            index = currentDog % 2;

                            JSONObject eyetypesGenes = eyetypes.getJSONObject(index);
                            String eyetypevalue = eyetypesGenes.getString("name");
                            boolean ishaveBKG = false;

                            JSONObject pupilGenes = pupilcolor.getJSONObject(index);
                            String pupilvalue = pupilGenes.getString("name");
                            int mouthscount = mouths.size();
                            index = currentDog % mouthscount;
                            JSONObject mouthsGenes = mouths.getJSONObject(index);
                            String mouthvalue = mouthsGenes.getString("name");

                            boolean haveCloth = false;
                            index = 0;
                            JSONObject wildGenes = wild.getJSONObject(index);
                            String wildvalue = wildGenes.getString("name");
                            int[] genes = new int[48];

                            setMutateGenes(bodyvalue, GENES_BODY, genes, 47);
                            setMutateGenes(patternvalue, GENES_PATTERN, genes, 43);
                            // eyecolor
                            setGenes(eyecolorvalue, GENES_EYECOLOR, genes, 39, 1);
                            randomGenes(eyecolors, 3, GENES_EYECOLOR, genes, 38);
                            // eyetype
                            setGenes(eyetypevalue, GENES_EYETYPE, genes, 35, 1);
                            randomGenes(eyetypes, 3, GENES_EYETYPE, genes, 34);
                            // BODY COLOR
                            setMutateGenes(bodycolorvalue, GENES_BODECOLOR, genes, 31);
                            // PAT COLOR
                            setMutateGenes(patcolorvalue, GENES_PATCOLOR, genes, 27);
                            // SEC COLOR
                            if (ishaveBKG) {
                                setGenes(pupilvalue, GENES_SECONDCOLOR, genes, 23, 1);
                                for (int s = 0; s < 3; s++) {
                                    genes[22 - s] = 5;
                                }
                            } else {
                                for (int s = 0; s < 4; s++) {
                                    genes[23 - s] = 5;
                                }
                            }

                            // SEC COLOR
                            if (haveCloth) {
                                setGenes(wildvalue, GENES_WILD, genes, 19, 1);
                                for (int s = 0; s < 3; s++) {
                                    genes[18 - s] = 1;
                                }
                            } else {
                                for (int s = 0; s < 4; s++) {
                                    genes[19 - s] = 1;
                                }
                            }
                            // mouth
                            setGenes(mouthvalue, GENES_MOUTH, genes, 15, 1);
                            randomGenes(mouths, 3, GENES_MOUTH, genes, 14);

                            mouthsGenes = mouths.getJSONObject(1);
                            mouthvalue = mouthsGenes.getString("name");
                            setGenes(mouthvalue, GENES_MOUTH, genes, 11, 4);
                            setGenes(mouthvalue, GENES_MOUTH, genes, 7, 4);
                            setGenes(mouthvalue, GENES_MOUTH, genes, 3, 4);
                            // System.out.println("genes！" + genes);
                            String binaryStr = "";
                            for (int m = 0; m < 48; m++) {
                                binaryStr += toBinaryString(genes[m]);
                            }
                            String newGenes = "0000" + binaryString2hexString(binaryStr);
                            createKittyByGenes(request, newGenes, "" + currentDog);
                            BigInteger bigInt = new BigInteger(newGenes, 16);
                            System.err.println("BigInteger" + bigInt.toString(10));
                            object.put("" + currentDog, newGenes);
                            allGensStrings += "Kitty" + currentDog + " Genes:" + newGenes + "\r\n";
                            currentDog++;
                        }
                    }
                }
            }
        }

        String currentPath = Tools.currentPath(request);
        String filePath = currentPath + "image/gene.json";
        try {
            writeFile(filePath, allGensStrings);
            System.out.println("genes！" + object.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
